package com.kehao.leetcode.jzoffer;

import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Kehao.Chen
 * @version 1.0
 * @date 2022/6/10 9:51
 */
public class JZSolution060 {

    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer,Integer> numToCount = new HashMap<>();
        for (int num : nums) {
            Integer before = numToCount.computeIfAbsent(num, key->0);
            numToCount.put(num,before+1);
        }
        List<Integer> collect = numToCount.values().stream().sorted((v1, v2) -> v2 - v1).limit(k).collect(Collectors.toList());
        List<Integer> result = numToCount.keySet().stream().filter(key -> collect.contains(numToCount.get(key))).collect(Collectors.toList());
        int[] resultArray = new int[result.size()];
        for (int i = 0; i < result.size(); i++) {
            resultArray[i] = result.get(i);
        }
        return resultArray;
    }

    public int[] topKFrequent2(int[] nums, int k) {
        HashMap<Integer,Integer> numToCount = new HashMap<>();
        PriorityQueue<Integer> queue = new PriorityQueue<>((k1,k2)->numToCount.get(k2)-numToCount.get(k1));

        for (int num : nums) {
            Integer before = numToCount.computeIfAbsent(num, key->0);
            numToCount.put(num,before+1);
        }
        for (Integer key : numToCount.keySet()) {
            queue.add(key);
        }
        int[] result = new int[k];
        for (int i = 0; i < k; i++) {
            result[i] = queue.poll();
        }
        return result;
    }

}
